﻿using System;
using System.Collections;
using System.Reflection;
using log4net;
using log4net.Config;
using System.Xml.Serialization;
using System.IO;
using System.Xml;
using System.ServiceModel;
using System.ComponentModel;
using System.ServiceModel.Security;
using System.Collections.Generic;
using System.ServiceModel.Description;
using System.Configuration;
using System.Data.SqlClient;
using System.Data;


namespace HaiFang
{
    [Serializable]
    public class ProxyDocumentOcrTask
    {
        private static string PROCEDURE_QueryDocumentOcrTask = "QueryDocumentOcrTask";
        private static string PROCEDURE_OcrDocumentContent = "OcrDocumentContent";
        private static string PROCEDURE_InsertDocumentOcrTask = "InsertDocumentOcrTask";

        //@CurrUserID			int = null,					--管理员编号
        //@QueryRow			int=1						--查询数量
        public static IList<DocumentOcrTask> QueryDocumentOcrTask(int CurrUserID, int QueryRow)
        {
            IList<DocumentOcrTask> list = new List<DocumentOcrTask>();
            try
            {
                using (SqlHelper helper = new SqlHelper())
                {
                    #region 构造参数
                    string comandText = PROCEDURE_QueryDocumentOcrTask;
                    List<SqlParameter> Parameters = new List<SqlParameter>();
                    Parameters.Add((new SqlParameter("@CurrUserID", CurrUserID)));
                    Parameters.Add((new SqlParameter("@QueryRow", QueryRow)));
                    #endregion

                    #region 获取执行结果
                    DataTable dt = helper.ExecuteDataTable(comandText, CommandType.StoredProcedure, Parameters);
                    list = helper.GetObjects<DocumentOcrTask>(dt);
                    #endregion
                }
            }
            catch (Exception ex)
            {
                LogHelper.Writelog(LogType.LogType_Error, ex.Message, ex);
            }
            return list;
        }
        //@CurrUserID			int = null,					--管理员编号
        //@AutoID				bigint,
        //@FileContent		text,						--内容要包含文件名
        //@ErrorMSG			int	output					-- 200:错误  0：正确；其他：错误
        public static void OcrDocumentContent(int CurrUserID, int AutoID, string FileContent, out int ErrorMSG)
        {
            ErrorMSG = -1;
            try
            {
                using (SqlHelper helper = new SqlHelper())
                {
                    #region 构造参数
                    string comandText = PROCEDURE_OcrDocumentContent;
                    List<SqlParameter> Parameters = new List<SqlParameter>();
                    Parameters.Add((new SqlParameter("@CurrUserID", CurrUserID)));
                    Parameters.Add(new SqlParameter("@AutoID", AutoID));
                    Parameters.Add(new SqlParameter("@FileContent", FileContent));
                    Parameters.Add(new SqlParameter()
                    {
                        ParameterName = "@ErrorMSG",
                        SqlDbType = SqlDbType.Int,
                        Direction = ParameterDirection.Output,
                        Value = ErrorMSG
                    });
                    #endregion

                    #region 获取执行结果
                    helper.Execute(comandText, CommandType.StoredProcedure, Parameters);
                    #endregion

                    #region 获取output值
                    foreach (SqlParameter sp in Parameters)
                    {
                        if (sp.ParameterName == "@ErrorMSG")
                        {
                            ErrorMSG = helper.GetInt(sp.Value);
                            break;
                        }
                    }
                    #endregion
                }
            }
            catch (Exception ex)
            {
                LogHelper.Writelog(LogType.LogType_Error, ex.Message, ex);
            }
        }
        //@CurrUserID			int = null,					--管理员编号
        //@ProjectId			varchar(40),
        //@AutoID				bigint=0,					
        //@Language			tinyint,					--1:中文   2：英文
        //@DoBlackWhite		tinyint,					--1：黑白  2：非黑白
        //@DoColorFilter		tinyint,					--1：滤色  2：非滤色
        //@DoNoiseReduce		tinyint,					--1：降噪  2：非降噪
        //@DoExpand			tinyint,					--1：扩大  2：非扩大
        //@Description		varchar(128),
        //@ErrorMSG			int	output					-- 200:错误  0：正确；其他：错误	
        public static void InsertDocumentOcrTask(int CurrUserID, int ProjectId, int AutoID, int Language, int DoBlackWhite, int DoColorFilter, int DoNoiseReduce, int DoExpand, string Description, out int ErrorMSG)
        {
            ErrorMSG = -1;
            try
            {
                using (SqlHelper helper = new SqlHelper())
                {
                    #region 构造参数
                    string comandText = PROCEDURE_InsertDocumentOcrTask;
                    List<SqlParameter> Parameters = new List<SqlParameter>();
                    Parameters.Add((new SqlParameter("@CurrUserID", CurrUserID)));
                    Parameters.Add(new SqlParameter("@ProjectId", ProjectId));
                    Parameters.Add(new SqlParameter("@AutoID", AutoID));
                    Parameters.Add(new SqlParameter("@Language", Language));
                    Parameters.Add(new SqlParameter("@DoBlackWhite", DoBlackWhite));
                    Parameters.Add(new SqlParameter("@DoColorFilter", DoColorFilter));
                    Parameters.Add(new SqlParameter("@DoNoiseReduce", DoNoiseReduce));
                    Parameters.Add(new SqlParameter("@DoExpand", DoExpand));
                    Parameters.Add(new SqlParameter("@Description", Description));
                    Parameters.Add(new SqlParameter()
                    {
                        ParameterName = "@ErrorMSG",
                        SqlDbType = SqlDbType.Int,
                        Direction = ParameterDirection.Output,
                        Value = ErrorMSG
                    });
                    #endregion

                    #region 获取执行结果
                    helper.Execute(comandText, CommandType.StoredProcedure, Parameters);
                    #endregion

                    #region 获取output值
                    foreach (SqlParameter sp in Parameters)
                    {
                        if (sp.ParameterName == "@ErrorMSG")
                        {
                            ErrorMSG = helper.GetInt(sp.Value);
                            break;
                        }
                    }
                    #endregion
                }
            }
            catch (Exception ex)
            {
                LogHelper.Writelog(LogType.LogType_Error, ex.Message, ex);
            }
        }
        /// <summary>
        /// 统一处理文档和文件夹
        /// </summary>
        /// <param name="CurrUserID"></param>
        /// <param name="ProjectId"></param>
        /// <param name="request"></param>
        public static int InsertDocumentOcrTask(int CurrUserID, int ProjectId, DocumentOcrTaskRequest r)
        {
            int ErrorMSG = 0;
            if (r != null)
            {
                //int FolderID = 0;
                if (r.FileType > 1)
                {
                    //ProxyDocumentInfo.QueryDocumentFolderID(CurrUserID, ProjectId, string.Format("\\{0}", r.FilePath), out FolderID);
                    if (r.AutoID > 0)
                    {
                        //IList<DocumentInfo> list = ProxyDocumentInfo.QueryDocumentInfo(CurrUserID, ProjectId, FolderID, 2, string.Empty, 1, 0);
                        //if (list != null && list.Count > 0)
                        {
                            //for (int i = 0; i < list.Count; i++)
                            {
                                //DocumentInfo di = list[i];
                                //if (di != null && di.FolderID == FolderID)
                                {
                                    //if (di.FileName.ToLower() == r.FilePath.Substring(r.FilePath.LastIndexOf("\\") + 1).ToLower())
                                    {
                                        InsertDocumentOcrTask(CurrUserID, ProjectId,
                                           r.AutoID, r.Language, r.DoBlackWhite, r.DoColorFilter, r.DoNoiseReduce, r.DoExpand, r.Description, out ErrorMSG);
                                        //break;
                                    }
                                }
                            }
                        }
                    }
                }
                else
                {
                    //ProxyDocumentInfo.QueryDocumentFolderID(CurrUserID, ProjectId, string.Format("\\{0}\\", r.FilePath), out FolderID);
                    if (r.AutoID > 0)
                    {
                        IList<DocumentFolder> dflist = ProxyDocumentInfo.QueryDocumentFolder(CurrUserID, ProjectId);
                        InsertDocumentOcrSubTask(CurrUserID, ProjectId, r.AutoID, r, dflist);
                    }
                }
            }
            return ErrorMSG;
        }
        /// <summary>
        /// 递归处理子文件夹
        /// </summary>
        /// <param name="CurrUserID"></param>
        /// <param name="ProjectId"></param>
        /// <param name="FolderID"></param>
        /// <param name="r"></param>
        private static void InsertDocumentOcrSubTask(int CurrUserID, int ProjectId, int FolderID, DocumentOcrTaskRequest r, IList<DocumentFolder> dflist)
        {
            IList<DocumentInfo> list = ProxyDocumentInfo.QueryDocumentInfo(CurrUserID, ProjectId, FolderID, 2, string.Empty, 1, 0);
            if (list != null && list.Count > 0)
            {
                for (int i = 0; i < list.Count; i++)
                {
                    DocumentInfo di = list[i];
                    if (di != null)
                    {
                        int FileType = ProxyDocumentInfo.GetDocumentFileType(di.FileExt);
                        if (FileType == 4 || FileType == 5 || FileType == 2 || FileType == 3)
                        {
                            //只处理图片和pdf
                            int ErrorMSG = -1;
                            InsertDocumentOcrTask(CurrUserID, ProjectId, di.AutoID, r.Language, r.DoBlackWhite,
                                r.DoColorFilter, r.DoNoiseReduce, r.DoExpand, r.Description, out ErrorMSG);
                            LogHelper.Writelog(LogType.LogType_Info, string.Format("Insert Document OCR Task.ErrorMSG:{0}", ErrorMSG), null);
                        }
                    }
                }
            }

            if (dflist != null && dflist.Count > 0)
            {
                for (int j = 0; j < dflist.Count; j++)
                {
                    DocumentFolder df = dflist[j];
                    if (df != null)
                    {
                        if (df.PrevFolderID == FolderID)
                        {
                            InsertDocumentOcrSubTask(CurrUserID, ProjectId, df.AutoID, r, dflist);
                        }
                    }
                }
            }
        }
    }

    [Serializable]
    public class DocumentOcrTask
    {
        public int AutoID { get; set; }
        public string GUID { get; set; }
        public int ProjectID { get; set; }
        public int FileID { get; set; }
        public string FileName { get; set; }
        public string FileExt { get; set; }
        public string FilePath { get; set; }
        public int Language { get; set; }
        public int DoBlackWhite { get; set; }
        public int DoColorFilter { get; set; }
        public int DoNoiseReduce { get; set; }
        public int DoExpand { get; set; }
        public int StatusFlag { get; set; }
        public DateTime CreateTime { get; set; }
        public string Description { get; set; }
    }

    [Serializable]
    public class DocumentOcrTaskRequest
    {
        public int AutoID { get; set; }
        public int FileType { get; set; }
        public string FilePath { get; set; }
        public int Language { get; set; }
        public int DoBlackWhite { get; set; }
        public int DoColorFilter { get; set; }
        public int DoNoiseReduce { get; set; }
        public int DoExpand { get; set; }
        public string Description { get; set; }
    }
}